#include "QRedirectStream.h"

#include <iostream>
#include <streambuf>
#include <string>

QRedirectStream::QRedirectStream(std::ostream &stream, QTextEdit* text_edit) : m_stream(stream)
{
	logWindow = text_edit;
	m_buf     = stream.rdbuf();
	stream.rdbuf(this);
}

QRedirectStream::~QRedirectStream()
{
	// output anything that is left
	if (!m_string.empty()) {		
		emit sendString(QString::fromLocal8Bit(m_string.c_str()));
	}

	m_stream.rdbuf(m_buf);
}

int QRedirectStream::overflow(int_type v)
{
	if (v == '\n')
	{
		emit sendString(QString::fromLocal8Bit(m_string.c_str()));

		m_string.erase(m_string.begin(), m_string.end());
	}
	else
		m_string += v;

	return v;
}

std::streamsize QRedirectStream::xsputn(const char *p, std::streamsize n)
{
	m_string.append(p, p + n);

	int tmp = std::string::npos;

	int pos = 0;
	while (pos != std::string::npos)
	{
		pos = m_string.find('\n');
		if (pos != std::string::npos)
		{
			std::string tmp(m_string.begin(), m_string.begin() + pos);

			emit sendString(QString::fromLocal8Bit(tmp.c_str()));

			m_string.erase(m_string.begin(), m_string.begin() + pos + 1);
		}
	}

	return n;
}